package com.ruoyi.util;

import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.*;
import java.util.Map;

public class WordUtils {

    public static String createDoc(Map<String, Object> data,FreeMarkerConfigurer freeMarkerConfigurer,String templeName,String fileName,String sourceAdr) throws IOException {
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        try {
            Template template = getTemplate(templeName,freeMarkerConfigurer);
            File output = new File(sourceAdr);
            if(!output.exists()){
                output.mkdir();
            }
            String adr = sourceAdr+ File.separator + fileName;
            fos = new FileOutputStream(output + File.separator + fileName);
            osw = new OutputStreamWriter(fos,"UTF-8");
            Writer bufferedWriter = new BufferedWriter(osw);
            template.process(data, bufferedWriter);
//            System.out.println("Word document generated successfully.");
            return adr;
        } catch (Exception e) {
//            System.out.println("错误信息"+e.getMessage());
        }finally {
            // 关闭输出流
            if(null != osw){
                osw.close();
            }
            if(null != fos){
                fos.close();
            }
        }

        return null;

    }

    public static Template getTemplate(String templeName, FreeMarkerConfigurer freeMarkerConfigurer) throws IOException {
        // 创建 Configuration 实例
//        Configuration cfg = new Configuration(Configuration.VERSION_2_3_31);
//        //不使用缓存
////                cfg.setTemplateUpdateDelay(0);
//        TemplateLoader templateLoader = null;
//        cfg.setDefaultEncoding("UTF-8");
//        templateLoader=new ClassTemplateLoader(WordUtils.class,sourceAdr);
//        cfg.setTemplateLoader(templateLoader);
        freeMarkerConfigurer.getConfiguration().setDefaultEncoding("UTF-8");
        Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templeName,"UTF-8");
        return template;
    }
}
